package com.heisenhub.uua.hander;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
public class HubOnAuthenticationSuccesHandler extends SavedRequestAwareAuthenticationSuccessHandler {



    private RequestCache requestCache = new HttpSessionRequestCache();
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SavedRequest savedRequest = this.requestCache.getRequest(request, response);
        if (savedRequest == null) {
            super.onAuthenticationSuccess(request, response, authentication);
            return;
        }
        String targetUrlParameter = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            this.requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);
            return;
        }
        clearAuthenticationAttributes(request);
        // Use the DefaultSavedRequest URL
        String targetUrl = savedRequest.getRedirectUrl();
        if(savedRequest instanceof DefaultSavedRequest && targetUrl.contains("oauth/authorize?")){
            DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) savedRequest;
            String gatewayUrl = request.getHeader("origin");
            targetUrl = gatewayUrl + "/uua/oauth/authorize?" + defaultSavedRequest.getQueryString() ;  //OAUTH 授权码模式走网关   不然云原生上有问题 重定向不过去
            log.info("【targetUrl】 {}" ,targetUrl);
        }
        getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }
}
